package eval.results;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Calendar;
import eval.utilities.configuration.ExperimentConfiguration;

/**
 * Writes the results into a file
 * 
 * @author Nicolo' M. Calcavecchia <calcavecchia@elet.polimi.it>
 * @author Amit Peled   <amit.kapina@gmail.com>
 * @author Igal Kaufman <igal.kaufman@gmail.com>  
 * */
public class ExperimentSerializer {

	public final static String PLACEMENT_FOLDER = 
			ExperimentConfiguration.getSingleton().placementLogsPath;

	/**
	 * Writes the file
	 * 
	 * @param resFileName
	 * @param resultsData
	 */
	public void writeExperiment(String resFileName,IResultsData resultsData) {
		try {
			FileOutputStream fout = new FileOutputStream(PLACEMENT_FOLDER
					+ generateFileName(resFileName,resultsData));
			ObjectOutputStream oos = new ObjectOutputStream(fout);
			oos.writeObject(resultsData);
			oos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Generate the result file name to RES
	 * 
	 * @param resFileName
	 * @param resultsData
	 * @return the file name
	 */
	public static String generateFileName(String resFileName, IResultsData resultsData) {
		String fileName = resultsData.getEngineType() + "_"
				+resFileName
				+ ".res";
		return fileName;
	}

	/**
	 * Generate the result file name with date
	 * 
	 * @return the file name
	 */
	public static String generateFileName() {
		Calendar now = Calendar.getInstance();
		String fileName = now.get(Calendar.DAY_OF_MONTH) + "-"
				+ (now.get(Calendar.MONTH)+1) + "-" 
				+ now.get(Calendar.YEAR) + "_"
				+ now.get(Calendar.HOUR_OF_DAY) + "-"
				+ now.get(Calendar.MINUTE) + "-" + now.get(Calendar.SECOND);
		return fileName;
	}

	/**
	 * Generate the result file name to CSV
	 * 
	 * @param resFileName
	 * @param resultsData
	 * @return the file name
	 */
	public static String generateFileNameToCsv(String resFileName, IResultsData resultsData) {
		String fileName = resultsData.getEngineType() + "_"
				+"SN_" + resultsData.getSeedNumber() + "_"
				+ resFileName
				+ ".csv";
		return fileName;
	}

	/**
	 *  Generate the error file name to TXT
	 *  
	 * @param resFileName
	 * @param resultsData
	 * @return the file name
	 */
	public static String generateFileNameForErrorLogToCsv(String resFileName,IResultsData resultsData) {
		String fileName = "ERROR_LOG_"
				+ resFileName
				+ ".txt";
		return fileName;
	}

	/**
	 * Reads the file 
	 * 
	 * @param resultsFilePath
	 * @return ResultsData
	 */
	public IResultsData readExperimentFile(String resultsFilePath) {
		IResultsData resultsData = null;
		try {
			FileInputStream fin = new FileInputStream(resultsFilePath);
			ObjectInputStream ois = new ObjectInputStream(fin);
			resultsData = (IResultsData) ois.readObject();
			ois.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultsData;
	}
}
